package com.qf.servlet;

import com.qf.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Ypl
 * @version V1.0
 * @Project September-mavens
 * @Package com.qf.servlet
 * @Description:
 * @Date 2022/10/10 16:00
 */
@SuppressWarnings("all")
@Controller
public class UserServlet {

    /**
     * 登录认证
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public Result Login(String username,String password){
        try {

            //        获取主体对象
            Subject subject = SecurityUtils.getSubject();

            //对密码进行加密处理
            Md5Hash md5Hash = new Md5Hash(password, username, 1024);
            //将用户存放在token中，校验使用
            UsernamePasswordToken passwordToken = new UsernamePasswordToken(username, md5Hash.toString());

            subject.login(passwordToken);//会进入到用户名密码校验的类中

            System.out.println("是否有管理员角色:"+ subject.hasRole("管理员"));
            System.out.println("是否有新增用户权限:"+ subject.isPermitted("sys:user:add"));

        }catch (UnknownAccountException e) {
           e.printStackTrace();
            return Result.error("未知的用户");
        } catch (LockedAccountException e){
            e.printStackTrace();
            return Result.error("账户已锁定");
        }catch (CredentialsException e) {
            e.printStackTrace();
            return Result.error("密码错误");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return Result.error("用户名不能为空");
        }
        return Result.ok("登录成功");

    }
}
